<template>   
    <view class="wrap">
        <js-error mode="bottom" ref="jsError"></js-error>
        <xw-scan></xw-scan>
        <u-modal v-model="jhshow" title="本次盘点" @confirm="tjconfirm" :show-cancel-button="false" width="80%" @cancel="cancel" :show-confirm-button="false" :negative-top="570">
            <u-form class="form bg-white" :model="jhData" :rules="rules" ref="uForm" label-position="left">
                <u-form-item label="商品:" prop="viewCode" label-width="130"  :label-style="{'padding' : '0 10px' }">
                    {{ jhData.viewCode || '' }}
                </u-form-item>
                <u-form-item label="货位:" prop="posName" label-width="130"  :label-style="{'padding' : '0 10px' }">
                      {{ jhData.posName || '' }}
                </u-form-item>
                <u-form-item label="数量:" prop="frealqty" label-width="130" :label-style="{ 'font-weight': 'bold','color':'red','padding' : '0 10px' }">
                    <u-input v-model="jhData.frealqty"  type="digit"  placeholder="请输入"  clearable />
                </u-form-item>
                <u-form-item label="辅助属性:" prop="f109" label-width="200" v-if="isAdd" :label-style="{'padding' : '0 10px' }">
                    <!-- {{ jhData.f109 || '' }} -->
                       <u-input v-model="jhData.f109"  type="text"  placeholder="请输入"  clearable />
                </u-form-item>
                
            </u-form>
            <view class="form-footer">
                <u-button class="btn" type="primary" @click="tjconfirm">确认</u-button>
                <u-button class="btn" type="default" @click="cancel">关闭</u-button>
            </view>
        </u-modal>
    </view>
</template>
<script> 
export default {
    data() {
		return {
            jhshow: false,
            jhData: {
                frealqty: '',
                viewCode: '',
                cinvcode: '',
                poscode: '',
                f109: '',
                basInv: null,
                basPosition: null,
                posName: '',
            },
            // model: {
            //     basInv: {},
            //     basPosition: {},

            // },
            companyCode: '',
            whcode: '',
            barCode: "",
            isAdd: false,
            isScanPos: false,
            rules: {
				viewCode: [
					{
						required: true,
						message: '请扫描商品',
						trigger: ['change','blur'],
					}
				],
                frealqty: [
                    {
                        required: true,
                        message: '请输入数量',
                        trigger: ['change','blur'],
                    },
                    {
                        validator: (rule, value, callback) => {
                            if (value < 0) {
                                callback(new Error('数量不能小于0'));
                            } else {
                                callback();
                            }
                        }, trigger: ['change','blur']
                    }
                ],
                posName: [
                    {
                        required: true,
                        message: '请扫描货位',
                        trigger: ['change','blur'],
                    },
                ],

			},


        }
    },
    onLoad(params) {

    },
    onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
    onShow() {
        // console.log('页面开启（onLoad）广播监听事件：xwscan')
        // 开启广播监听事件
        uni.$on('xwscan', this.BroadcastScanningToObtainData)
    },
    onHide() {
        // console.log('页面销毁（onUnload）广播监听事件：xwscan')
        // 销毁广播监听事件
        uni.$off('xwscan', this.BroadcastScanningToObtainData)
    },
    onUnload() {
        // console.log('页面销毁（onUnload）广播监听事件：xwscan')
        // 销毁广播监听事件
        uni.$off('xwscan', this.BroadcastScanningToObtainData)
    },
    methods: {
            // 初始化表单规则
            initFormRules() {
                this.$nextTick(() => {
                    if (this.$refs.uForm) {
                        this.$refs.uForm.setRules(this.rules);
                    } else {
                        setTimeout(() => {
                            this.initFormRules();
                        }, 100);
                    }
                });
            },
            getJhshow(){
                this.jhshow = true;
                this.$nextTick(() => {
                    this.$set(this.jhData, 'frealqty', this.jhData?.frealqty || '');
                    this.$set(this.jhData, 'posName', this.jhData?.basPosition?.posName || '');
                    this.$set(this.jhData, 'poscode', this.jhData?.basPosition?.posCode || '');
                    this.$set(this.jhData, 'viewCode', this.jhData.basInv ? "【"+this.jhData.basInv.viewCode+"】"+this.jhData.basInv.invName : '');
                    this.$set(this.jhData, 'cinvcode', this.jhData?.basInv ? this.jhData.basInv.invCode : '');
                    if (!this.jhData?.basPosition?.posCode) {
                        this.isScanPos = true;
                    }

                });
                uni.$on('xwscan', this.BroadcastScanningToObtainData);
                this.initFormRules();
            },
            BroadcastScanningToObtainData(res) {
                // 处理扫描数据的逻辑
                console.log('Modal组件接收到扫描数据:', res);
			    let barcode = res.code
				
				if(!this.jhshow){
					return false;
				}
				
				//判断条形码长度是否大于3
				if(barcode.length > 3){
					//去除换行符
					let newString = barcode.replace('\n;', '');
					
					this.barCode = newString;
					
					this.smconfirm();
				}
            },
            smconfirm(){
                let _that = this;
                _that.focus = false
                let InventoryPrefix = _that.vuex_config.InventoryPrefix;
                let PositionPrefix = _that.vuex_config.PositionPrefix;
                let InvBarType = _that.vuex_config.InvBarType;
                let PosBarType = _that.vuex_config.PosBarType;
                let bar = encodeURIComponent(this.barCode);
                // 如果this.jhData.basPosition.posName不为空，则不再调用接口
                if (!this.isScanPos) {
                    this.$u.toast('货位已经存在');
                    return false;
                }

                if (bar.indexOf(PositionPrefix) != -1) {
                    this.$u.api.ktnw.getBarInfo({
                        barCode: bar,
                        barType: PosBarType,
                        whCode: this.whcode || ''
                    }).then((res) => {
                        if (res.result == 'true') {
                            if(res.data?.basPos?.treeLeaf == '0') {
								this.$forceUpdate()
								_that.sendMp3('sb');
								let message = '请扫描末级货位'
								_that.$refs.jsError.showError("", message, "error");
								return;
							}
                            _that.sendMp3('cg');

                            if (!this.jhData.basPosition) {
                                this.$set(this.jhData, 'basPosition', {});
                            }
                            this.$set(this.jhData, 'posName', res.data.basPos.posName);
                            this.jhData.poscode = res.data.basPos.posCode;
                            this.isScanPos = true;

            
                        } else {
                            _that.sendMp3('sb');
                            let message = res.message
                            _that.$refs.jsError.showError("", message, "error");
                            setTimeout(() => {
                                _that.focus = true;
                            }, 500)
                        }
                        this.barCode = ''
                    })
                } else {
                    let barCode = this.invCode(bar, this.companyCode)
                    this.$u.api.ktnw.getBarInfo({
                        barCode: barCode,
                        barType: InvBarType,
                        companyCode: this.companyCode
                    }).then((res) => {
                        if (res.result == 'true') {
                            
                            if(res.data.basInv){
                                _that.sendMp3('cg');
                                setTimeout(() => {
                                    this.barCode = ''
                                    // _that.focus = true;
                                }, 500)
                                console.log('res.data.basInv',res.data.basInv)
                                // this.query['viewCode'] = res.data.basInv?res.data.basInv.viewCode:''
                                // this.query['invName'] = res.data.basInv?res.data.basInv.invName:''
                                // this.$forceUpdate()
                                // this.query.pageNo = 1;
                                // this.loadData();
                                // 方案1：使用Vue.set确保响应式更新（推荐用于动态属性）
                                const viewCodeValue = res.data.basInv?'【'+res.data.basInv.viewCode+'】'+res.data.basInv.invName:'';
                                this.$set(this.jhData, 'viewCode', viewCodeValue);
                                this.jhData.cinvcode = res.data.basInv?res.data.basInv.invCode:'';
                                console.log('jhData:', this.jhData);

                                // 强制更新视图（如果其他方法都不行的话）
                                // this.$forceUpdate();
                                // this.$forceUpdate()
                                _that.sendMp3('cg');
                                setTimeout(() => {
                                    this.barCode = ''
                                    // _that.focus = true;
                                }, 500)
                                
                            }else{
                                _that.sendMp3('sb');
                                let message = '请扫描正确的商品编码'
                                _that.$refs.jsError.showError("", message, "error");
                            }
                        } else {
                            _that.sendMp3('sb');
                            let message = res.message
                            _that.$refs.jsError.showError("", message, "error");
                            setTimeout(() => {
                                this.barCode = ''
                                // _that.focus = true;
                            }, 500)
                        }
                        this.barCode = ''
        
                    })
                }
            },
            invCode(bar, companyCode) {
                let InventoryPrefix = this.vuex_config.InventoryPrefix;
                if (bar.indexOf(InventoryPrefix) != -1) {
                    return bar
                } else {
                    let code = `inv_${companyCode}_${bar}`
                    return code
                }
            },
            sendMp3(name) {
                console.log("=====testClick=====");
                let src = '/static/jeesite/' + name + '.mp3';
                //实例化声音
                const Audio = uni.createInnerAudioContext();
                Audio.autoplay = true;
                Audio.src = src; //音频地址
                Audio.play(); //执行播放
                Audio.onError((res) => {
                    console.log(res.errMsg);
                    console.log(res.errCode);
                });
                Audio.onPause(function() {
                    console.log('end');
                    Audio.destroy();
                });
            },
            cancel() {
                this.jhshow = false;
                uni.$off('xwscan', this.BroadcastScanningToObtainData);
                // 通知父组件取消事件
                // this.$emit('tjcancel');
            },
        	tjconfirm(){
                if(this.isAdd){
                    this.toAddSubmit();
                } else {
                    this.toEditSubmit();
                }
			},
            toEditSubmit(){
                var _that = this;

                // 先进行表单验证
                this.$refs.uForm.validate(valid => {
                    if (!valid) {
                        this.$u.toast('请填写正确的信息');
                        return;
                    }

                    // 验证通过，执行保存操作
                    _that.performSave();
                });
            },
            performSave() {
                var _that = this;

                this.$u.api.ktnw.savePdData({
                    id: this.jhData.id,
                    frealqty: this.jhData.frealqty,
                    poscode: this.jhData.poscode,
                }).then(res => {
                    if (res.result == 'true') {
                        _that.sendMp3('cg');
                        this.$u.toast(res.message);
                        _that.jhData = {}
                        this.jhshow = false
                        // 通知父组件刷新数据
                        this.$emit('tjconfirm');
                        uni.$off('xwscan', this.BroadcastScanningToObtainData)
                    } else {
                        _that.sendMp3('sb');
                        this.$refs.jsError.showError('', res.message, 'error');
                    }
                });
            },
            toAddSubmit(){
                this.$refs.uForm.validate(valid => {
                    console.log('验证结果', valid); // true 表示对整个表单验证无误
                    if (valid) {
                        this.$u.api.ktnw.createPdData({
                            djno: this.jhData.djno,
                            cinvcode: this.jhData.cinvcode,
                            frealqty: this.jhData.frealqty,
                            poscode: this.jhData.poscode,
                            f109: this.jhData.f109,
                        }).then(res => {
                            if (res.result == 'true') {
                                this.$u.toast(res.message);
                                this.jhData = {}
                                this.jhshow = false
                                // 通知父组件刷新数据
                                this.$emit('tjconfirm');
                                uni.$off('xwscan', this.BroadcastScanningToObtainData)
                            } else {
                                this.$refs.jsError.showError('', res.message, 'error');
                            }
                        });

                    } else {
                        this.$u.toast('您填写的信息有误，请根据提示修正。');
                    }
                });
            }
    }
};

</script>
<style lang="scss" scoped>
    .form-footer {
        margin: 0;
        padding: 0 10rpx;
        padding-bottom: 20rpx;
    }
</style>